package com.googlecode.moneyManager.dao.hib;

import com.googlecode.moneyManager.dao.SecurityValueDAO;
import com.googlecode.moneyManager.exceptions.DataAccessException;
import com.googlecode.moneyManager.model.Currency;
import com.googlecode.moneyManager.model.SecurityValue;
import com.googlecode.moneyManager.model.TypeSecurityValue;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.Calendar;
import java.util.List;

/**
 * Author: Sergiy Doroshenko
 * Date: Apr 27, 2010
 * Time: 11:08:04 PM
 */
public class SecurityValueDAOHib extends HibernateDaoSupport implements SecurityValueDAO  {



    public String create(SecurityValue value) throws DataAccessException {
        getHibernateTemplate().persist(value);
        return value.getId();
    }

    public void saveOrUpdate(SecurityValue value) throws DataAccessException {
        getHibernateTemplate().saveOrUpdate(value);
    }

    public void merge(SecurityValue value) throws DataAccessException {
          throw  new UnsupportedOperationException();
    }

    public void delete(SecurityValue value) throws DataAccessException {
          throw  new UnsupportedOperationException();
    }

    public SecurityValue get(String id) throws DataAccessException {
        throw  new UnsupportedOperationException();
    }

    public List<SecurityValue> getAll() throws DataAccessException {
        throw  new UnsupportedOperationException();
    }

    public SecurityValue getSecurityValueByDate(Calendar date, TypeSecurityValue type, Currency currency) {
        //@Todo rewrite to juda time
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        cal1.set(date.get(Calendar.YEAR), date.get(Calendar.MONDAY), date.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal2.set(date.get(Calendar.YEAR), date.get(Calendar.MONDAY), date.get(Calendar.DAY_OF_MONTH) + 1, 0, 0, 0);

        Criteria c = getSession().createCriteria(SecurityValue.class).
                add(Restrictions.eq("type", type)).
                add(Expression.between("date", cal1, cal2)).
                createCriteria("amount").add(Restrictions.eq("currency", currency));
        return (SecurityValue) c.uniqueResult();
    }
}
